package com.ffyc.resale.service;

import com.ffyc.resale.dao.ForumCommentDao;
import com.ffyc.resale.model.ForumComment;
import com.ffyc.resale.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

// 帖子评论业务层
@Service
@Transactional(rollbackFor = Exception.class)
public class ForumCommentService {

    @Autowired
    ForumCommentDao forumCommentDao;

    /**
     * 新增
     */
    public void add(ForumComment forumComment,String userToken) {
        // 添加评论时，修订日期格式
        // comment.setTime(DateUtil.now());
        forumComment.setTime(new Date());
        if (forumComment.getPid() != null) {  // 表示这是一个回复
            ForumComment pComment = this.selectById(forumComment.getPid());  // 查出父级的评论
            if (pComment == null) {
                return;
            }
            if (pComment.getRootId() != null) {  // 这不是根节点
                forumComment.setRootId(pComment.getRootId());
            } else {
                forumComment.setRootId(pComment.getId());  // 这是根节点
            }
        }
        forumComment.setUserId(JWTUtil.getUser(userToken).getId());
        forumCommentDao.insert(forumComment);
    }

    /**
     * 前台递归删除
     */
    public void deepDelete(Integer pid) {
        forumCommentDao.deleteById(pid);
        List<ForumComment> children = forumCommentDao.selectByPid(pid);
        // 判断children集合是不是空的
        //if (CollUtil.isNotEmpty(children)) {
        if (!children.isEmpty()) {
            for (ForumComment forumComment : children) {
                pid = forumComment.getId();
                this.deepDelete(pid);
            }
        }
    }

    /**
     * 根据ID查询
     */
    public ForumComment selectById(Integer id) {
        return forumCommentDao.selectById(id);
    }

    public List<ForumComment> selectTree(Integer fid) {
        List<ForumComment> commentList = forumCommentDao.selectTree(fid);
        // 筛选出最外层的节点
        List<ForumComment> rootList = commentList.stream().filter(comment -> comment.getPid() == null).collect(Collectors.toList());
        for (ForumComment root : rootList) {
            Integer rootId = root.getId();
            List<ForumComment> children = commentList.stream().filter(comment -> rootId.equals(comment.getRootId())).collect(Collectors.toList());
            root.setChildren(children);
        }
        return rootList;
    }

    public Integer selectCount(Integer fid) {
        return forumCommentDao.selectCount(fid);
    }
}
